package com.snail.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snail.constants.RabbitMqConstants;
import com.snail.feign.SysUserClient;
import com.snail.mapper.BizCollectionWorksMapper;
import com.snail.mapper.BizFilesMapper;
import com.snail.model.pojo.media.BizCollectionWorks;
import com.snail.model.pojo.media.BizFiles;
import com.snail.model.pojo.media.BizWorks;
import com.snail.model.pojo.user.SysUser;
import com.snail.model.query.media.WorksPageQuery;
import com.snail.model.query.media.WorksReviewPageQuery;
import com.snail.model.vo.media.BizWorksReviewVo;
import com.snail.model.vo.media.BizWorksVo;
import com.snail.result.Result;
import com.snail.service.BizWorksService;
import com.snail.mapper.BizWorksMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author Monica
* @description 针对表【biz_works(作品主表)】的数据库操作Service实现
* @createDate 2025-08-16 15:15:44
*/
@Service
public class BizWorksServiceImpl extends ServiceImpl<BizWorksMapper, BizWorks>
    implements BizWorksService{

    @Autowired
    private BizWorksMapper bizWorksMapper;
    @Autowired
    private BizFilesMapper bizFilesMapper;
    @Autowired
    private BizCollectionWorksMapper bizCollectionWorksMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private SysUserClient sysUserClient;

    @Override
    public BizWorks createWorks(BizWorks bizWorks) {
        int i = bizWorksMapper.insert(bizWorks);
        bizWorksMapper.selectById(bizWorks.getId());
        rabbitTemplate.convertAndSend(RabbitMqConstants.MINIO_REVIEW_EXCHANGE, RabbitMqConstants.MINIO_REVIEW_ROUTING_KEY, bizWorks);
        return bizWorks;
    }

    @Override
    public IPage<BizWorksVo> getWorksList(WorksPageQuery worksPageQuery) {
        int pageNum = Math.max(worksPageQuery.getPageNum(), 1);
        int pageSize = Math.min(Math.max(worksPageQuery.getPageSize(), 10), 100);
        IPage<BizWorks> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<BizWorks> queryWrapper = new LambdaQueryWrapper<>();

        if (worksPageQuery.getIsCharge() != null) {
            queryWrapper.eq(BizWorks::getIsCharge, worksPageQuery.getIsCharge());
        }

        if (worksPageQuery.getStatus() != null) {
            queryWrapper.eq(BizWorks::getStatus, worksPageQuery.getStatus());
        }

        if (StrUtil.isNotBlank(worksPageQuery.getWorksName())) {
            queryWrapper.like(BizWorks::getWorksName, worksPageQuery.getWorksName());
        }

        Long userId = worksPageQuery.getUserId();
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        queryWrapper.eq(BizWorks::getUserId, userId);

        queryWrapper.orderByDesc(BizWorks::getCreateTime);

        IPage<BizWorks> resultPage = bizWorksMapper.selectPage(page, queryWrapper);

        IPage<BizWorksVo> voPage = resultPage.convert(bizWorks -> {
            BizWorksVo bizWorksVo = new BizWorksVo();
            BeanUtil.copyProperties(bizWorks, bizWorksVo);

            // 关联查询文件信息（添加空指针保护）
            String fileMd5 = bizWorks.getFileMd5();
            if (StrUtil.isNotBlank(fileMd5)) {
                // 只查询需要的字段，减少数据传输
                LambdaQueryWrapper<BizFiles> fileQuery = new LambdaQueryWrapper<>();
                fileQuery.eq(BizFiles::getFileMd5, fileMd5)
                        .select(BizFiles::getPreviewUrl); // 只查预览地址字段

                BizFiles bizFiles = bizFilesMapper.selectOne(fileQuery);
                if (bizFiles != null) {
                    bizWorksVo.setVideoUrl(bizFiles.getPreviewUrl());
                } else {
                    // 文件不存在时的默认处理
                    bizWorksVo.setVideoUrl("");
                }
            }
            return bizWorksVo;
        });

        return voPage;
    }

    @Override
    public List<BizWorks> getWorksListByUserId(Long id,String name) {
        LambdaQueryWrapper<BizWorks> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizWorks::getUserId, id);
        queryWrapper.eq(BizWorks::getStatus, 3);
        if (StrUtil.isNotBlank(name)) {
            queryWrapper.like(BizWorks::getWorksName, name);
        }

        return baseMapper.selectList(queryWrapper);
    }


    @Override
    public List<BizWorks> getCollectionWorks(Integer collectionId) {
        if (collectionId == null) {
            return null;
        }
        LambdaQueryWrapper<BizCollectionWorks> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizCollectionWorks::getCollectionId, collectionId);
        List<BizCollectionWorks> bizCollectionWorks = bizCollectionWorksMapper.selectList(queryWrapper);
        ArrayList<BizWorks> bizWorks = new ArrayList<>();
        for (BizCollectionWorks bizCollectionWork : bizCollectionWorks) {
            BizWorks works = bizWorksMapper.selectById(bizCollectionWork.getWorksId());
            bizWorks.add(works);
        }
        return bizWorks;


    }

    @Override
    public BizWorksVo getWorksById(Long id) {

        return bizWorksMapper.getWorksById(id);
    }

    @Override
    public IPage<BizWorksReviewVo> getWorksReviewList(WorksReviewPageQuery worksReviewPageQuery) {
        Page<BizWorks> bizWorksPage = new Page<>(worksReviewPageQuery.getPageNum(), worksReviewPageQuery.getPageSize());
        LambdaQueryWrapper<BizWorks> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(worksReviewPageQuery.getWorksName())) {
            queryWrapper.like(BizWorks::getWorksName, worksReviewPageQuery.getWorksName());
        }
        if (StrUtil.isNotBlank(worksReviewPageQuery.getDescription())) {
            queryWrapper.like(BizWorks::getDescription, worksReviewPageQuery.getDescription());
        }
        queryWrapper.eq(BizWorks::getStatus, 2);
        queryWrapper.orderByDesc(BizWorks::getCreateTime);
        IPage<BizWorks> resultPage = bizWorksMapper.selectPage(bizWorksPage, queryWrapper);

        // 关联查询文件信息（添加空指针保护）
        return resultPage.convert(bizWorks -> {
            BizWorksReviewVo bizWorksReviewVo = new BizWorksReviewVo();
            BeanUtil.copyProperties(bizWorks, bizWorksReviewVo);

            // 关联查询文件信息（添加空指针保护）
            Long userId = bizWorks.getUserId();
            if (userId != null) {
                Result<SysUser> userResult = sysUserClient.getUserById(userId);
                if (userResult != null) {
                    bizWorksReviewVo.setUsername(userResult.getData().getUsername());
                }
            }
            // 关联查询文件信息（添加空指针保护）
            String fileMd5 = bizWorks.getFileMd5();
            if (StrUtil.isNotBlank(fileMd5)) {
                // 只查询需要的字段，减少数据传输
                LambdaQueryWrapper<BizFiles> fileQuery = new LambdaQueryWrapper<>();
                fileQuery.eq(BizFiles::getFileMd5, fileMd5)
                        .select(BizFiles::getPreviewUrl); // 只查预览地址字段

                BizFiles bizFiles = bizFilesMapper.selectOne(fileQuery);
                if (bizFiles != null) {
                    bizWorksReviewVo.setVideoUrl(bizFiles.getPreviewUrl());
                } else {
                    // 文件不存在时的默认处理
                    bizWorksReviewVo.setVideoUrl("");
                }
            }

            return bizWorksReviewVo;
        });
    }
}




